package cn.lin.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author qmp
 * @date 2024/12/4 17:30
 */
public class UploadVideoUtil {

    private static final String ACCESS_KEY_ID = "LTAI5tRtgVxTeERw3wqRaFd1";
    private static final String ACCESS_KEY_SECRET = "goWREaK0TsD0YkyksaqkmlVi8DcWH5";
    private static final String vodRegion = "cn-beijing" ;

    //访问URL
    static String url = "https://red-travel-platform.oss-cn-beijing.aliyuncs.com";

    // Convert MultipartFile to File
    private static File convertMultipartFileToFile(MultipartFile multipartFile) throws IOException {
        File convFile = new File(multipartFile.getOriginalFilename());
        convFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(multipartFile.getBytes());
        fos.close();
        return convFile;
    }

    // Initialize VOD client
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    // Create video upload request
    public static CreateUploadVideoResponse createUploadVideo(DefaultAcsClient vodClient, String fileName, String title) throws ClientException {
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setFileName(fileName);
        request.setTitle(title);
        request.setSysReadTimeout(1000);
        request.setSysConnectTimeout(1000);
        return vodClient.getAcsResponse(request);
    }

    // Initialize OSS client
    public static OSSClient initOssClient(JSONObject uploadAuth, JSONObject uploadAddress) {
        String endpoint = uploadAddress.getString("Endpoint");
        String accessKeyId = uploadAuth.getString("AccessKeyId");
        String accessKeySecret = uploadAuth.getString("AccessKeySecret");
        String securityToken = uploadAuth.getString("SecurityToken");
        return new OSSClient(endpoint, accessKeyId, accessKeySecret, securityToken);
    }

    // Upload file to OSS
    public static String uploadLocalFile(OSSClient ossClient, JSONObject uploadAddress, String localFile) {
        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");
        /*String objectName = "video/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + System.currentTimeMillis() + ".mp4" ;*/
        File file = new File(localFile);
        ossClient.putObject(bucketName, objectName, file);
        return url + "/" + objectName ;
    }

    // Decode Base64 string
    private static String decodeBase64(String data) {
        return new String(Base64.decodeBase64(data));
    }

    public static String uploadVideo(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return "Please select a file to upload" ;
        }

            // Save the file locally temporarily
            File tempFile = convertMultipartFileToFile(file);

            // Initialize VOD client and get upload address and credentials
            DefaultAcsClient vodClient = initVodClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            CreateUploadVideoResponse createUploadVideoResponse = createUploadVideo(vodClient,file.getOriginalFilename(),file.getOriginalFilename());

            // Execute successfully will return VideoId, UploadAddress, and UploadAuth
            String videoId = createUploadVideoResponse.getVideoId();

            // Parse to get result objects
            JSONObject uploadAuth = JSONObject.parseObject(decodeBase64(createUploadVideoResponse.getUploadAuth()));
            JSONObject uploadAddress = JSONObject.parseObject(decodeBase64(createUploadVideoResponse.getUploadAddress()));

            // Use UploadAuth and UploadAddress to initialize OSS client
            OSSClient ossClient = initOssClient(uploadAuth, uploadAddress);

            // Upload file, note that this is synchronous upload which will block waiting
            String url = uploadLocalFile(ossClient, uploadAddress, tempFile.getAbsolutePath());

            // Clean up temporary file
            tempFile.delete();

            System.out.println("url +  " + url);

            return url ;

    }

}
